package com.chenfan.magic.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenfan.magic.config.IdcProperties;
import com.chenfan.magic.dao.DatasourceCensusMapper;
import com.chenfan.magic.entity.IdcDatasourceCensus;
import com.chenfan.magic.service.IDatasourceCensusService;
import com.chenfan.magic.service.IDatasourceService;
import com.chenfan.magic.utils.DateUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 服务实现类
 *
 * @author troy
 */
@Service
@AllArgsConstructor
public class DatasourceCensusServiceImpl extends ServiceImpl<DatasourceCensusMapper, IdcDatasourceCensus> implements IDatasourceCensusService {

    private IDatasourceService datasourceService;

    private final IdcProperties idcProperties;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void record(String datasourceId) {
        String daily = DateUtil.DATE_FORMAT.format(new Date());
        IdcDatasourceCensus datasourceCensus = this.getOne(Wrappers.<IdcDatasourceCensus>query()
                .lambda()
                .eq(IdcDatasourceCensus::getDatasourceId, datasourceId)
                .eq(IdcDatasourceCensus::getServiceId, idcProperties.getName())
                .eq(IdcDatasourceCensus::getRecordDaily, daily));
        if (datasourceCensus == null) {
            datasourceCensus = new IdcDatasourceCensus();
            datasourceCensus.setServiceId(idcProperties.getName());
            datasourceCensus.setDatasourceId(datasourceId);
            datasourceCensus.setNumSum(1L);
            datasourceCensus.setRecordDaily(daily);
            datasourceCensus.setRecordNearlyTime(new Date());
            this.save(datasourceCensus);
        } else {
            datasourceCensus.setNumSum(datasourceCensus.getNumSum() + 1);
            datasourceCensus.setRecordNearlyTime(new Date());
            this.updateById(datasourceCensus);
        }
        datasourceService.updateApplyTime(datasourceId);
    }
}
